const fs = require('fs')
var zh = require('./lang/zh.js')
const request = require('superagent')
const requestProxy = require('superagent-proxy')
requestProxy(request)
main()

async function main() {
  // const ip = await getIp()
  const ip = ''
  for (var item in zh) {
    if (typeof zh[item] === 'object') {
      for (var index in zh[item]) {
        let time = Math.ceil(Math.random() * (30 - 5) + 5)
        console.log(`延迟${time}秒后进行翻译`)
        const str = await sleep(fanyi, [zh[item][index], ip], time)
        try {
          console.log(
            `${zh[item][index]}翻译已完成：`,
            str.body.sentences[0].trans
          )
          zh[item][index] = str.body.sentences[0].trans
        } catch (error) {
          console.log('翻译内容不正确！查看内容：', str)
        }
      }
    }
  }
  console.log('所有翻译已完成', zh)
  saveJs('km.js', zh)
}

// 翻译
// http://translate.google.cn/translate_a/single?client=gtx&dt=t&dj=1&ie=UTF-8&sl=auto&tl=zh&q=hello
async function fanyi(str, _ip) {
  console.log(`正在翻译：${str}`)
  let ip = _ip
  try {
    return await request
      .get('http://translate.google.cn/translate_a/single')
      .set('Content-Type', 'text/html;charset=utf-8')
      .timeout({
        response: 10000,
        deadline: 60000,
      })
      .query({
        client: 'gtx',
        dt: 't',
        dj: '1',
        ie: 'UTF-8',
        sl: 'auto',
        tl: 'km',
        q: str,
      })
      .proxy(ip)
  } catch (error) {
    if (error.timeout && error.timeout === 10000) {
      console.log('请求超时，重新请求', error)
      return await fanyi(str, ip)
    } else {
      console.log('出错啦！重新获取ip...', error)
      ip = await sleep(getIp, [ip], 5)
      return await fanyi(str, ip)
    }
  }
}

// 保存js
function saveJs(filename, data) {
  var str = 'export default ' + JSON.stringify(data)
  fs.writeFile(`./lang/${filename}`, str, function (err) {
    if (err) {
      throw err
    }
    console.log(`${filename}导出成功！`)
  })
}

// 延迟一定时间
async function sleep(fn, key, time) {
  return new Promise((resolve) => {
    setTimeout(() => resolve(fn(...key)), time * 1000 || 1200)
  })
}

// 获取ip地址
async function getIp(ip) {
  try {
    console.log('正在获取ip...')
    const result = await request.get('https://ip.jiangxianli.com/api/proxy_ip')
    const newIp = `http://${result.body.data.ip}:${result.body.data.port}`
    if (newIp === ip) {
      console.log('ip获取与上次相同,等待1分钟之后重新获取ip..')
      return sleep(getIp, [newIp], 60)
    }
    console.log(`成功获取ip：${newIp}`)
    return newIp
  } catch (error) {
    // 暂停1分钟后重新获取ip
    console.log('ip获取出错，等待1分钟之后重新获取ip...')
    return sleep(getIp, [ip], 60)
  }
}
